/**
 * Created with IntelliJ IDEA.
 * User: zzl
 * Date: 12-11-28
 * To change this template use File | Settings | File Templates.
 */
(function ($) {

    $.proxyAll = function (map, context) {
        for (var key in map) {
            var fn = map[key];
            if (typeof fn == 'string') {
                fn = context[fn];
            }
            map[key] = $.proxy(fn, context);
        }
    };

    $.addPluginFn = function (fnName, Type, defaultOptions) {
        return $.fn[fnName] = function (options) {

            if (typeof options == 'string') {
                var args = Array.prototype.slice.call(arguments, 1);
                var result;
                for (var n = 0; n < this.length; n++) {
                    var obj = $(this[n]).data(fnName);
                    if(obj) {
                        var fn = obj[options];
                        if(!fn) {
                            if(options == 'get') {
                                result = obj;
                            }
                            else {
                                throw new Error("cannot call " + options + ' on a ' + fnName + ' object');
                            }
                        }
                        else {
                            result = fn.apply(obj, args);
                        }
                    }
                }
                return result;
            }
            return this.each(function () {
                if($(this).data(fnName)) {
                    console.log('component ' + fnName + ' already attached on ' +
                        this.nodeName + '(' + $(this).text() + ')');
                    return;
                }
                var combinedOptions = $.extend({}, defaultOptions || {}, options);
                $(this).data(fnName, new Type(this, combinedOptions));
            });
        };
    };

    $.fn.reverse = [].reverse;

    $.fn.dataAttr = function(key, value) {
        this.data(key, value);
        this.attr('data-' + key, value);
    };

    $.fn.containsEvent = function(e) {
        for(var n = 0; n < this.length; n++) {
            var el = this[n];
            if(el == e.target || $.contains(el, e.target)) {
                return true;
            }
        }
        return false;
    };

})(jQuery);